package com.xnfh.planting.ui.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.view.get
import androidx.recyclerview.widget.GridLayoutManager
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.SmartGlideImageLoader
import com.xnfh.common.adapter.SelectImageAdapter
import com.xnfh.common.bean.Record
import com.xnfh.common.utils.FullyGridLayoutManager
import com.xnfh.common.utils.GlideEngine
import com.xnfh.framework.Constants
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.framework.utils.TimeUtils
import com.xnfh.image.ImageHelper
import com.xnfh.image.ImageUrl
import com.xnfh.planting.R
import com.xnfh.planting.databinding.ActivityAddXuntianBinding
import com.xnfh.planting.viewmodel.AddXunTianViewModel

/**
 * @Description:添加巡田记录
 * @Author: ziheng
 * @CreateDate: 2023/12/18 15:37
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/12/18 15:37
 * @UpdateRemark: 更新说明
 */
class AddXunTianActivity : BaseActivity<ActivityAddXuntianBinding>(), View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.activity_add_xuntian

    companion object {
        const val REQUEST_CODE = 10001
        const val RESPONSE_CODE = 10002
        fun start(context: Activity, requestCode: Int, bundle: Bundle? = null) {
            val intent = Intent(context, AddXunTianActivity::class.java)
            if (bundle != null) {
                intent.putExtra("bundle", bundle)
            }
            context.startActivityForResult(intent, requestCode)
        }
    }

    private var fieldDetailBean: Record? = null

    private var viewModel: AddXunTianViewModel? = null
    private var imageAdapter: SelectImageAdapter? = null

    /**
     * 打开选择图片的页面
     */
    private var photoList = ArrayList<Photo>()

    //巡田时间
    private var xtData: String? = null


    override fun init(savedInstanceState: Bundle?) {
        setHeaderTitle(getString(R.string.start_xun_tian))
        mBind.addXuntianSubmit.setOnClickListener(this)
        val bundleExtra = intent.getBundleExtra("bundle")
        fieldDetailBean = bundleExtra?.getSerializable("data") as Record
        //设置选择图片的recycle
        val fullyGridLayoutManager =
            FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        imageAdapter = SelectImageAdapter(6)
        imageAdapter?.setNewInstance(null)//先设置一个null，内部会处理添加➕的图片
        mBind.addXuntianRecycle.layoutManager = fullyGridLayoutManager
        mBind.addXuntianRecycle.adapter = imageAdapter
        //设置基本信息展示
        setDetailMessage()

        imageAdapter?.setCallBack(object : SelectImageAdapter.SelectImageCallBack {
            /**
             * 选择图片
             */
            override fun addImageClick() {
                openPic()
            }

            /**
             * 查看大图
             */
            override fun showBigImage(position: Int, imageView: ImageView) {
                XPopup.Builder(this@AddXunTianActivity).asImageViewer(
                    imageView, position,
                    imageAdapter?.data?.toMutableList() as List<Any>?,
                    { popupView, position ->
                        popupView.updateSrcView(mBind.addXuntianRecycle[position].findViewById(com.xnfh.common.R.id.item_select_image_view) as ImageView)
                    }, SmartGlideImageLoader()
                ).show()
            }

            /**
             * 删除指定图片
             */
            override fun deleteImagePosition(position: Int) {
                photoList.removeAt(position)
            }
        })

    }

    override fun observe() {
        viewModel = AddXunTianViewModel()
        viewModel?.addXunTianData?.observe(this, object : BaseStateObserver<Any>(null) {
            override fun getRespDataStart() {
                super.getRespDataStart()
                showLoadingDialog()
            }

            override fun getRespDataError() {
                super.getRespDataError()
                dismissLoadingDialog()
            }

            override fun getRespDataSuccess(it: Any) {
                super.getRespDataSuccess(it)
                TipsToast.showTips(R.string.add_xt_success)
                setResult(RESPONSE_CODE)
                finish()
            }
        })
    }

    override fun onClick(v: View?) {
        when (v) {
            mBind.addXuntianSubmit -> {
                if (xtData == null) {
                    TipsToast.showTips(R.string.xt_data_isnull)
                    return
                }
                viewModel?.requestAddRecord(
                    photoList,
                    fieldDetailBean?.fieldId,
                    fieldDetailBean?.plantCropId,
                    xtData!!,
                    mBind.addXuntianEdit.text.toString()
                )
            }
        }
    }

    private fun openPic() {
        EasyPhotos.createAlbum(
            this,
            true,
            false,
            GlideEngine.get()
        )//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
            .setFileProviderAuthority(Constants.SELECT_PIC)//参数说明：见下方`FileProvider的配置`
            .setCount(6)
            .setSelectedPhotos(photoList)
            .start(object : SelectCallback() {
                override fun onResult(photos: java.util.ArrayList<Photo>?, isOriginal: Boolean) {
                    photoList.clear()
                    photos?.let { photoList.addAll(it) }
                    val list = ArrayList<String>()
                    if (photos != null && photos.size > 0) {
                        photos.forEach {
                            list.add(it.path)
                        }
                    }
                    imageAdapter?.setNewInstance(list)
                }

                override fun onCancel() {
                    LogUtil.d("取消选择图片回调")
                }

            })
    }

    /**
     * 设置地块详情信息
     */
    private fun setDetailMessage() {
        ImageHelper.instance?.loadNetImg(
            this, ImageUrl.BASEURL + fieldDetailBean?.fileURL, mBind.addXuntianPic,
            com.xnfh.common.R.mipmap.image_error, com.xnfh.common.R.mipmap.image_error
        )
        mBind.addXuntianName.text = fieldDetailBean?.fieldName
        mBind.addXuntianPzAndMu.text =
            "${fieldDetailBean?.plantCropName}  |  ${fieldDetailBean?.areaMu}${getString(R.string.field_detail_mu)}"
        mBind.addXuntianAddress.text = fieldDetailBean?.address
        //获取当前的时间作为巡田时间
        xtData = TimeUtils.getCurrData(TimeUtils.dateFormatYMDHMS)
        mBind.addXuntianTime.text =
            getString(R.string.xun_tian_time) + xtData
    }
}